import { ResponseCode } from "@/common/Responsetypes";
import { getTokenStore, setTokenStore } from "@/utils/storage/tokenStore";
import Request, {
  type HttpRequestConfig,
  type HttpResponse,
} from "luch-request";

const http = new Request({
  baseURL: import.meta.env.VITE_BASE_API,
});

http.interceptors.request.use((config: HttpRequestConfig) => {
  const token = getTokenStore();
  if (token) {
    // config.header = config.header || {};
    config.header!.Authorization = token;
  }

  return config;
});

http.interceptors.response.use(
  (response: HttpResponse) => {
    // console.log(response);

    const userApiList = ["/users/login", "/users/register", "/users/whoami"];
    // e.g. /users/login
    const url = response.config.url || "";
    const isUserApi = userApiList.some((api) => url.includes(api));
    if (isUserApi) {
      const token: string = response.header.authorization;
      if (token) {
        setTokenStore(token);
      }
    }

    uni.hideLoading();

    const responseData = response.data;
    if (
      responseData.code !== ResponseCode.PASS &&
      responseData.code !== ResponseCode.NOT_ALLOW
    ) {
      uni.showToast({
        icon: "error",
        title: responseData.msg || "响应错误",
        duration: 2000,
      });
    } else if (
      responseData.code === ResponseCode.NOT_ALLOW &&
      url === "/users/whoami"
    ) {
      uni.showToast({
        icon: "error",
        title: "登录过期",
        duration: 2000,
      });
    } else if (responseData.code === ResponseCode.NOT_ALLOW) {
      uni.showToast({
        icon: "error",
        title: "请先登录",
        duration: 2000,
      });

      setTimeout(() => {
        const page = getCurrentPages();
        const currentPage = page[page.length - 1].$page.fullPath;
        uni.reLaunch({
          url: `/pages/login/login?redirect=${currentPage}`,
        });
      }, 1000);
    }

    return responseData;
  },
  (error: object) => {
    return Promise.reject(error);
  }
);

export default http;
